package com.oracle.malldemo.servlet.users;

import com.alibaba.fastjson.JSON;
import com.oracle.malldemo.domain.Users;
import com.oracle.malldemo.view.JsonData;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(value="/users/login")
public class UsersLoginServlet extends UsersServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();

        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            Users loginSuccessUser = null;
            if ((loginSuccessUser = usersService.login(username, password)) != null) {
                //返回用户之前，把用户名密码置空。
                loginSuccessUser.setPassword("");
                JsonData result = JsonData.success("登录成功！", loginSuccessUser);
                out.write(JSON.toJSONString(result));
            } else {
                JsonData result = JsonData.fail("登录失败，请检查用户名或者密码是否正确！", null);
                out.write(JSON.toJSONString(result));
            }
            out.flush();
            out.close();
        }catch(Exception ex){
            ex.printStackTrace();
            JsonData result = JsonData.fail("程序出现异常！", null);
            out.write(JSON.toJSONString(result));
            out.flush();
            out.close();
        }
    }
}
